package com.mcc.web.controller.system;

import java.util.List;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.mcc.common.exception.CustomException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mcc.common.annotation.Log;
import com.mcc.common.core.controller.BaseController;
import com.mcc.common.core.domain.AjaxResult;
import com.mcc.common.core.domain.entity.SysRole;
import com.mcc.common.core.domain.model.LoginUser;
import com.mcc.common.core.page.TableDataInfo;
import com.mcc.common.enums.BusinessType;
import com.mcc.common.utils.SecurityUtils;
import com.mcc.common.utils.ServletUtils;
import com.mcc.common.utils.StringUtils;
import com.mcc.framework.web.service.SysPermissionService;
import com.mcc.framework.web.service.TokenService;
import com.mcc.system.service.ISysRoleService;
import com.mcc.system.service.ISysUserService;

/**
 * 角色信息
 *
 * @author gxy
 */
@Api(tags = "角色")
@ApiSort(16)
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    @ApiOperation("获取角色列表")
    @ApiOperationSupport(order = 1)
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    public AjaxResult<TableDataInfo<SysRole>> list(SysRole role) {
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    @ApiOperation("获取角色列表(分页)")
    @ApiOperationSupport(order = 2)
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/page")
    public AjaxResult<TableDataInfo<SysRole>> page(SysRole role) {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    @ApiOperation("根据角色编号获取详细信息")
    @ApiOperationSupport(order = 3)
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/get/{roleId}")
    public AjaxResult<SysRole> getInfo(@PathVariable Long roleId) {
        return AjaxResult.success(roleService.selectRoleById(roleId));
    }

    @ApiOperation("新增角色")
    @ApiOperationSupport(order = 4)
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SysRole role) {
        if (!roleService.checkRoleNameUnique(role)) {
            throw new CustomException("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            throw new CustomException("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(SecurityUtils.getUsername());
        return toAjax(roleService.insertRole(role));

    }

    @ApiOperation("修改角色")
    @ApiOperationSupport(order = 5)
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody SysRole role) {
        if (!roleService.checkRoleNameUnique(role)) {
            throw new CustomException("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            throw new CustomException("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());

        if (roleService.updateRole(role) > 0) {
            // 更新缓存用户权限
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (StringUtils.isNotNull(loginUser.getUser()) && !SecurityUtils.isAdmin(loginUser.getUser().getUserId())) {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return AjaxResult.success();
        }
        throw new CustomException("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    @ApiOperation("删除角色")
    @ApiOperationSupport(order = 6)
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove/{roleIds}")
    public AjaxResult remove(@PathVariable Long[] roleIds) {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    @ApiOperation("获取角色选择框列表")
    @ApiOperationSupport(order = 7)
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        return AjaxResult.success(roleService.selectRoleList(null));
    }
}
